package cn.cxj.org.service.impl;

import cn.cxj.basic.exception.BusinessException;
import cn.cxj.basic.service.impl.BaseServiceImpl;
import cn.cxj.org.domain.Employee;
import cn.cxj.org.domain.Shop;
import cn.cxj.org.mapper.EmployeeMapper;
import cn.cxj.org.mapper.ShopMapper;
import cn.cxj.org.service.IEmployeeService;
import cn.cxj.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.internet.MimeMessage;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;
    
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void settlement(Shop shop) {
        // 校验
        // 1.两次输入的密码是否一致
        Employee admin = shop.getAdmin();
        if(!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BusinessException("两次密码输入不一致!");
        }
        // 2.输入的用户名是否与数据库重复
        Employee temp = employeeMapper.loadByUsername(admin.getUsername());
        if(temp != null){
            throw new BusinessException("用户已经存在,请直接登录!如果忘记密码,请找回密码!");
        }
        // 注册
        // 保存employee,返回自增id
        //employeeMapper.save(admin);
        admin.setState(0);
        employeeService.add(admin);
        // 给店铺设置admin_id并保存shop,返回自增id
        shop.setAdmin(admin);
        shop.setState(0);
        shopMapper.save(shop);
        // 修改employee的shop_id
        admin.setShop_id(shop.getId());
        //employeeMapper.update(admin);
        employeeService.update(admin);
    }

    @Override
    public void auditSuccess(Shop shop) throws Exception{
        Long id = shop.getId();
        // 审核通过
        Shop shopTemp = shopMapper.loadById(id);
        System.out.println(shopTemp);
        // 将状态改为1
        shopTemp.setState(1);
        shopMapper.update(shopTemp);
        // 给admin中的邮箱地址发送邮件,携带修改状态链接
        String email = shopTemp.getAdmin().getEmail();
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        helper.setFrom("53999356@qq.com");
        helper.setSubject("激活邮件");
        helper.setText("<a href='http://localhost:8081/#/login?id=" + shopTemp.getAdmin().getId()  + "'>点击激活账号</a>",true);
        helper.setTo("53999356@qq.com");
        // 发送邮件
        javaMailSender.send(mimeMessage);

    }
}
